package com.lion.appletrip;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.lion.appletrip.model.ListViewItem.CoveredCountry;
import com.lion.appletrip.model.ListViewItem.Day;
import com.lion.appletrip.model.ListViewItem.ListViewData;
import com.lion.appletrip.model.ListViewItem.Poi;
import com.lion.appletrip.model.ListViewItem.PoiInfosCount;
import com.lion.appletrip.model.ListViewItem.User;
import com.lion.appletrip.model.ListViewItem.Waypoint;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.romainpiel.titanic.library.Titanic;
import com.romainpiel.titanic.library.TitanicTextView;
import com.xinbo.utils.GsonUtils;
import com.xinbo.utils.HTTPUtils;
import com.xinbo.utils.UILUtils;
import com.xinbo.utils.VolleyListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("InflateParams")
public class ListViewActivity extends Activity
{
	

	private PullToRefreshListView mPullRefreshListView;
	private TwoAdapter twoAdapter;
	private List<Day> days = new ArrayList<Day>();
	private List<Waypoint> waypoints = new ArrayList<Waypoint>();
	private Day day = new Day();
	private ListView mListView;
	private int i=0;
	private ImageView ivImage;
	private ImageView ivAvatarM;
	private TextView tvName;
	private TextView tvLastDay;
	private TextView tvDayCount;
	private TextView tvMileage;
	private TextView tvRecom;
	private TextView tvSights;
	private TextView tvRestaurant;
	private TextView tvNameUser;
	private TextView tvHotel;
	private TextView tvMall;
	private TextView tvNameCove;
	private ImageView ivIcon;
	private LinearLayout mlion2048;
	private View lion009;
	private TitanicTextView ivLoading;
	private Titanic titanic;
	private boolean isLast;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_view);
		initUI();
		Intent intent = getIntent();
		long id = intent.getLongExtra("urlId", 0);
		String url = "http://api.breadtrip.com/trips/" + id + "/waypoints/";
		initData(url);
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener()
        {

	        @Override
	        public void onLastItemVisible()
	        {	
		        if (i<days.size()-1)
		        {
		        	i += 1;
			        day = days.get(i);
			        List<Waypoint> waypoints2 = day.getWaypoints();
			        waypoints.addAll(waypoints2);
		        }else {
		        	if (!isLast)
                    {
		        		i=days.size()-1;
		        		day = days.get(i);
		        		List<Waypoint> waypoints2 = day.getWaypoints();
		        		waypoints.addAll(waypoints2);
                    }
		        	isLast=true;
				}
		        twoAdapter.notifyDataSetChanged();
	        }
        });
		findViewById(R.id.btn_close_listview).setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		findViewById(R.id.btn_cillect).setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				
				
			}
		});
	}

	@SuppressLint("InflateParams")
    private void initUI()
	{
		mPullRefreshListView= (PullToRefreshListView) findViewById(R.id.listView1_listviewactivity);
		View headview = getLayoutInflater().inflate(R.layout.activity_list_view_headview, null);
		lion009 = findViewById(R.id.lion0000001);
		ivLoading = (TitanicTextView)findViewById(R.id.loading_listview);
		titanic = new Titanic();
		titanic.start(ivLoading);
		initHeadview(headview);
		twoAdapter = new TwoAdapter();
		mListView = mPullRefreshListView.getRefreshableView();
		mListView.addHeaderView(headview, null, false);
		mListView.setAdapter(twoAdapter);
	}



	private void initHeadview(View headview)
    {
	    ivImage = (ImageView) headview.findViewById(R.id.iv_trackpoints_thumbnail_image);
	    ivAvatarM = (ImageView) headview.findViewById(R.id.iv_avatar_m_listview_item);
	    tvName = (TextView) headview.findViewById(R.id.tv_name);
	    tvLastDay = (TextView) headview.findViewById(R.id.tv_last_day_listview);
	    tvDayCount = (TextView) headview.findViewById(R.id.tv_day_count_listview);
	    tvMileage = (TextView) headview.findViewById(R.id.tv_mileage_listview);
	    tvRecom = (TextView) headview.findViewById(R.id.tv_recommendations_listview);
	    tvSights = (TextView) headview.findViewById(R.id.tv_sights_listview);
	    tvRestaurant = (TextView) headview.findViewById(R.id.tv_restaurant_listview);
	    tvNameUser = (TextView) headview.findViewById(R.id.tv_name_user);
	    tvHotel = (TextView) headview.findViewById(R.id.tv_hotel_listview);
	    tvMall = (TextView) headview.findViewById(R.id.tv_mall_listview);
	    tvNameCove = (TextView) headview.findViewById(R.id.tv_name_covered_countries);
	    ivIcon = (ImageView) headview.findViewById(R.id.iv_icon);
	    mlion2048 = (LinearLayout) headview.findViewById(R.id.lion2048);
    }



	class TwoAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{
			return waypoints.size();
		}

		@Override
		public Object getItem(int position)
		{
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			return 0;
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
				
			View layout = null;
			ViewHolder viewHolder = null;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				layout = getLayoutInflater().inflate(
				        R.layout.activity_list_view_listview_item, null);
				viewHolder.ivTop = layout.findViewById(R.id.iv_top_lianjie);
				viewHolder.tvDayDays = (TextView) layout
				        .findViewById(R.id.tv_day_days);
				viewHolder.ivPhotos = (ImageView) layout
				        .findViewById(R.id.iv_photos_waypoints);
				viewHolder.tvText = (TextView) layout
				        .findViewById(R.id.tv_text_waypoints);
				viewHolder.tvLocalTime = (TextView) layout
				        .findViewById(R.id.tv_local_time_waypoints);
				viewHolder.tvNamePoi = (TextView) layout
				        .findViewById(R.id.tv_name_poi_waypoints);
				viewHolder.viewTop = layout.findViewById(R.id.lion_day_day_up);
				layout.setTag(viewHolder);
			} else
			{
				layout = convertView;
				viewHolder = (ViewHolder) layout.getTag();
			}
			
			 if (position == 0)
			{
				viewHolder.ivTop.setVisibility(View.INVISIBLE);
				viewHolder.viewTop.setVisibility(View.VISIBLE);
				viewHolder.tvDayDays.setText("第1天 " + day.getDate());
			} else
			{
				viewHolder.ivTop.setVisibility(View.VISIBLE);
				viewHolder.viewTop.setVisibility(View.GONE);
			}
			
			
			if (position>0)
            {
				Integer dayCurrent = waypoints.get(position).getDay();
				Integer dayPre = waypoints.get(position-1).getDay();
				if (dayPre != dayCurrent)
				{
					viewHolder.viewTop.setVisibility(View.VISIBLE);
					viewHolder.ivTop.setVisibility(View.VISIBLE);
					viewHolder.tvDayDays.setText("第" + dayCurrent + "天  " + day.getDate());
				} else
				{
					viewHolder.viewTop.setVisibility(View.GONE);
				}
            }
			
			Waypoint waypoint = waypoints.get(position);
			
			String text = waypoint.getText();
			String photoS = waypoint.getPhotoS();
			String localTime = waypoint.getLocalTime();
			Poi poi = waypoint.getPoi();
			viewHolder.tvText.setText(text);
			viewHolder.tvLocalTime.setText(localTime);
			if (poi != null)
			{
				String name = poi.getName();
				viewHolder.tvNamePoi.setText(name);
			} else
			{
				viewHolder.tvNamePoi.setVisibility(View.GONE);
			}
			if ("".equals(photoS))
			{
				viewHolder.ivPhotos.setVisibility(View.GONE);
			} else
			{
				UILUtils.displayImageNoAnim(photoS, viewHolder.ivPhotos);
			}
			return layout;
		}

	}

	class ViewHolder
	{
		private View ivTop;
		private TextView tvDayDays;
		private ImageView ivPhotos;
		private TextView tvText;
		private TextView tvLocalTime;
		private TextView tvNamePoi;
		private View viewTop;
	}

	private void initData(String url)
	{
		HTTPUtils.get(this, url, new VolleyListener()
		{

			@Override
			public void onResponse(String json)
			{
				days.clear();
				ListViewData listViewData = GsonUtils.parseJSON(json,
				        ListViewData.class);
				days = listViewData.getDays();
				day = days.get(0);
				waypoints = day.getWaypoints();
				initHeadViewData(listViewData);
				twoAdapter.notifyDataSetChanged();
				titanic.cancel();
				ivLoading.setVisibility(View.GONE);
				lion009.setVisibility(View.VISIBLE);
			}

			@Override
			public void onErrorResponse(VolleyError arg0)
			{

			}
		});
		
	}
	protected void initHeadViewData(ListViewData listViewData)
    {
	    String trackpointsThumbnailImage = listViewData.getTrackpointsThumbnailImage();
	    User user = listViewData.getUser();
	    String name = listViewData.getName();
	    String firstDay = listViewData.getFirstDay();
	    Integer dayCount = listViewData.getDayCount();
	    Double mileage = listViewData.getMileage();
	    DecimalFormat df = new DecimalFormat("#");
	    String format = df.format(mileage);
	    Integer re = listViewData.getRecommendations();
	    PoiInfosCount poiInfosCount = listViewData.getPoiInfosCount();
	    Integer sights = poiInfosCount.getSights();
	    Integer restaurant = poiInfosCount.getRestaurant();
	    Integer hotel = poiInfosCount.getHotel();
	    Integer mall = poiInfosCount.getMall();
	    String nameUser = user.getName();
	    String avatarM = user.getAvatarM();
	    tvLastDay.setText(firstDay);     
	    tvName.setText(name);
	    tvNameUser.setText(nameUser);  
	    tvDayCount.setText(dayCount+"天");
	    tvMileage.setText(format);
	    tvRecom.setText(re+"人喜欢");
	    tvSights.setText(sights+"景点");
	    tvRestaurant.setText(restaurant+"餐饮");
	    tvHotel.setText(hotel+"住宿");
	    tvMall.setText(mall+"购物");
	    UILUtils.displayImageNoAnim(avatarM, ivAvatarM);
	    UILUtils.displayImageNoAnim(trackpointsThumbnailImage, ivImage);
	    List<CoveredCountry> coveredCountries = listViewData.getCoveredCountries();
	    if (coveredCountries.size()>0)
        {	
	    	StringBuffer sb = new StringBuffer();
	        CoveredCountry cov = coveredCountries.get(0);
	        String icon = cov.getIcon();
	        String nameCov = cov.getName();
	        UILUtils.displayImageNoAnim(icon, ivIcon);
	        sb.append(nameCov);
	        if (coveredCountries.size()>1)
            {
	        	for (int i = 1; i <  coveredCountries.size(); i++)
	        	{
	        		View layout = getLayoutInflater().inflate(R.layout.activity_list_view_headview_item, null);
	        		ImageView mImageView = (ImageView) layout.findViewById(R.id.iv_icon2);
	        		CoveredCountry cov2 = coveredCountries.get(i);
	        		String iconAdd = cov2.getIcon();
	        		String nameCovAdd = cov2.getName();
	        		sb.append("·"+nameCovAdd);
	        		UILUtils.displayImageNoAnim(iconAdd, mImageView);
	        		@SuppressWarnings("unused")
                    LayoutParams layoutParams = layout.getLayoutParams();
	        		mlion2048.addView(layout);
	        	}
	            
            }
	        tvNameCove.setText(sb);
        }
    }

	@Override
	protected void onDestroy()
	{
		ImageLoader.getInstance().clearMemoryCache();
	    super.onDestroy();
	}
}
